import React, { useEffect, useState } from 'react';
import MenuList from './MenuList';

import { useDispatch, useSelector } from 'react-redux';
import Icon from '@/components/Icon';
import { Tooltip } from 'antd';
import useSyncState from '../hooks/useSyncState';

import LanguageListModal from '../Setting/LanguageListModal';

import BackgroundModal from '../Setting/BackgroundModal';
import AccpetCallMode from '../Setting/AccpetCallMode';
import AutoOtherWork from '../Setting/AutoOtherWork';
import { useTranslation } from 'react-i18next';
import CallProgress from '@/components/CallProgress';
import AfterWorkEnd from '@/components/Arrange';
import AgentService, { IStreamMode, IEvent } from '@/modules/Agent';
import { ICallProgressGroups } from '@/modules/interface';

import UserConfigDropdown from './UserConfigDropdown';
import StatusDropdown from './StatusDropdown';

import FloatAlert from '../Setting/FloatAlert';


interface UserConfigProps {
	agentName: string;
	changePageLayout?: (layout: string) => void;
}

const UserConfig = (props: UserConfigProps) => {
	const { t } = useTranslation();
	const { agentName, changePageLayout } = props;

	const { agent, session } = useSelector((state: any) => state);

	const [agentStatus, setagentStatus] = useState<string>('');

	const [agentStatusTips, setAgentStatusTips] = useState(t('not-checked-in'));

	const [showAgentTips, setShowAgentTips] = useState(false);

	const [menuIcon, setMenuIcon] = useState('#icon-widget-a-bianzu4beifen5');
	const [acceptCallVisiable, setAcceptCallVisiable] = useState(false);
	const [autoOtherWorkVisiable, setAutoOtherWorkVisiable] = useState(false);
	const [backGroundVisible, setBackGroundVisible] = useState<boolean>(false);

	const [languageVisible, setLanguageVisible] = useState<boolean>(false);

	const changeLayout = (layout: string) => {
		console.log(layout);

		changePageLayout && changePageLayout(layout);
	};
	const dispatch = useDispatch();

	const [visibleAgentDetails, setVisibleAgentDetails] = useSyncState<boolean>(false);

	const [settingVisible, setSettingVisible] = useSyncState<boolean>(false);

	const [floatAlertVisible, setFloatAlertVisible] = useState(false);

	const headerMenu = [
		{
			id: 1,
			icon: '#icon-widget-a-bianzu4beifen6',
			mode: 'middle'
		},
		{
			id: 2,
			icon: '#icon-widget-a-bianzu4beifen5',
			mode: 'full'
		},
		{
			id: 3,
			icon: '#icon-widget-a-bianzu4beifen4',
			mode: 'right'
		},
		{
			id: 4,
			icon: '#icon-widget-a-bianzu42',
			mode: 'left'
		}
	];

	const [menus, setMenus] = useState([
		{
			id: 1,
			icon: '#icon-widget-a-bianzu4',
			acitveIcon: '#icon-widget-a-bianzu411',
			classname: '',
			text: t('left-column'),
			isSelect: false,
			mode: 'left'
		},
		{
			id: 2,
			icon: '#icon-widget-a-bianzu4beifen',
			acitveIcon: '#icon-widget-a-bianzu4beifen1',
			classname: '',
			text: t('right-column'),
			isSelect: false,
			mode: 'right'
		},
		{
			id: 3,
			icon: '#icon-widget-a-bianzu4beifen2',
			acitveIcon: '#icon-widget-a-bianzu4beifen21',
			classname: '',
			text: t('left-right-column'),
			isSelect: true,
			mode: 'full'
		},
		{
			id: 4,
			icon: '#icon-widget-a-bianzu4beifen3',
			acitveIcon: '#icon-widget-a-bianzu4beifen31',
			classname: '',
			text: t('fold-up'),
			isSelect: false,
			mode: 'close'
		}
	]);

	useEffect(() => {
		if (AgentService.agentStatus.checkIn && !AgentService.agentStatus.ready && !AgentService.agentStatus.otherWork) {
			setagentStatus('checkIn');
			setAgentStatusTips(t('not-ready-status'));
		} else if (AgentService.agentStatus.ready) {
			setagentStatus('ready');
			setAgentStatusTips(t('ready-status'));
		} else if (AgentService.agentStatus.otherWork && !AgentService.agentStatus.ready) {
			setagentStatus('otherWork');
			if (session.sessionId) {
				setAgentStatusTips(t('book-break'));
			} else {
				setAgentStatusTips(AgentService.agentStatus.afterWork ? t('booked-break') : t('taking-break'));
			}
		} else if (!AgentService.agentStatus.checkIn && !AgentService.agentStatus.ready && !AgentService.agentStatus.otherWork) {
			setagentStatus('');
			// setAgentStatusTips(t('not-checked-in'));
			setAgentStatusTips(t('not-ready-status'));
		}
	}, [agent.status, session.sessionId, AgentService.agentStatus]);

	useEffect(() => {
		document.body.onclick = e => {
			if (visibleAgentDetails()) {
				setVisibleAgentDetails(false);
			}
			if (settingVisible()) {
				setSettingVisible(false);
			}
		};
	}, []);

	const { isCallProgressHidden } = AgentService.configure.preferenceSettings;

	const setAcceptCall = (mode: IStreamMode) => {
		AgentService.setAcceptCallMode({ ...AgentService.acceptCallMode, receiveMediaType: mode });
		setAcceptCallVisiable(false);
	};

	const chooseMenu = (item: { id: number; label: string; children: any[]; i18nKey: string }) => {
		switch (item.id) {
			case 1:
				setBackGroundVisible(true);
				break;
			case 2:
				setBackGroundVisible(true);
				break;
			case 3:
				setLanguageVisible(true);
				break;
			case 4:
				setAutoOtherWorkVisiable(true);
				break;
			case 5:
				setFloatAlertVisible(true);
			break;
				
			default:
				break;
		}
		//  dispatch(setBackgroundVisible(true));
	};

	const [progress, setProgress] = useSyncState<number>(AgentService.callProgress);

	const [progressGroups, setProgressGroups] = useSyncState<ICallProgressGroups[]>(AgentService.callProgressGroups);

	useEffect(() => {
		AgentService.addEventListener((info: any) => {
			if (info.event === IEvent.CALL_PROGRESS) {
				setProgress(info.data.data.total);
				setProgressGroups(info.data.data.groups);
			} else if (info.event === IEvent.REOPEN_FLOAT_WINDOW) {
                setFloatAlertVisible(true);
            }
		});

		return () => AgentService.removeEventListener();
	}, []);

	const setAutoOtherWork = () => {
		setAutoOtherWorkVisiable(false);
	};

	const { configure } = AgentService;

	return (
		<div className="widget-user-config">
			{AgentService.agentStatus.afterWork && AgentService.isSessionSummaryOn() ? <AfterWorkEnd /> : null}

			{/* 排队数 */}
			{!isCallProgressHidden && AgentService.agentStatus.checkIn ? <CallProgress progress={progress()} groups={progressGroups() || []} /> : null}

			{/* 折叠菜单 */}
			{!AgentService.configure.preferenceSettings.layoutConfigHidden && <MenuList menus={[]} changeLayout={changeLayout}></MenuList>}

			{/* 设置菜单 */}
			<UserConfigDropdown setSettingVisible={setSettingVisible} chooseMenu={chooseMenu}></UserConfigDropdown>
			{/* 用户状态 */}

			<Tooltip placement="bottom" title={agentStatusTips}>
				<span
					className="user"
					onClick={() => {
						setShowAgentTips(!showAgentTips);
					}}
				>
					<i className={`user-status-${agentStatus}`}></i>
					<Icon classname="icon-widget-yonghu"></Icon>
				</span>
			</Tooltip>

			{/* 用户名称 */}
			<StatusDropdown setVisibleAgentDetails={setVisibleAgentDetails}></StatusDropdown>

			{/** 语言设置 */}
			<LanguageListModal visible={languageVisible} cancel={() => setLanguageVisible(false)} onOK={() => setLanguageVisible(false)} />
			{/** 背景设置 */}
			<BackgroundModal visible={backGroundVisible} cancel={() => setBackGroundVisible(false)} onOK={() => setBackGroundVisible(false)} />
			{/* 接听设置 */}
			<AccpetCallMode visible={acceptCallVisiable} ok={setAcceptCall} cancel={() => setAcceptCallVisiable(false)} />
			{/* 自动小休设置 */}
			<AutoOtherWork visible={autoOtherWorkVisiable} ok={setAutoOtherWork} cancel={() => setAutoOtherWorkVisiable(false)}></AutoOtherWork>
			{/* 开启悬浮框提醒 */}
			<FloatAlert visible={floatAlertVisible} close={() => setFloatAlertVisible(false)} />
		</div>
	);
};

export default UserConfig;
